package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Gathering;
import cn.wolfcode.crm.domain.Officialstu;
import cn.wolfcode.crm.mapper.GatheringMapper;
import cn.wolfcode.crm.mapper.OfficialstuMapper;
import cn.wolfcode.crm.query.QueryForObject;
import cn.wolfcode.crm.service.IGatheringService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class GatheringService implements IGatheringService {
    @Autowired
    private GatheringMapper mapper;
    @Autowired
    private OfficialstuMapper officialstuMapper;

    public void insert(Gathering record) {
        mapper.insert(record);
    }

    public Gathering selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    public List<Gathering> selectAll() {
        return mapper.selectAll();
    }

    public void updateByPrimaryKey(Gathering record) {
        mapper.updateByPrimaryKey(record);
    }
    public PageResult query(QueryForObject qo) {
        int total = mapper.queryForCount(qo);
        if (total == 0) {
            return new PageResult();
        }
        List<Gathering> rows = mapper.queryForList(qo);

        return new PageResult(total, rows);
    }

    /**
     * 审核
     */
    @Override
    public void changeState(Long feeId,Long stuId) {
        //查询收款管理
        Gathering gathering = mapper.selectByPrimaryKey(feeId);

        //如果状态值为1，表示已审核
        if(gathering.getState() != 1) {
            Officialstu officialstu = officialstuMapper.selectByPrimaryKey(gathering.getStudent().getId());
            if (officialstu.getNoPay().compareTo(gathering.getTotalFee()) <= 0) {
                //如果本次付款>=未付款值，未付款设置为0 ，付款状态设置为1(已付清)，已付款设置为本次付款值加原已付款值
                officialstu.setPaidFee(officialstu.getPaidFee().add(gathering.getTotalFee()));
                officialstu.setNoPay(BigDecimal.ZERO);
                officialstu.setFeeState(1);
            } else {
                //如果未付款值>本次付款，未付款设置为两者相减 ，付款状态设置为0(未付清)，已付款设置为本次付款值加原已付款值
                officialstu.setPaidFee(officialstu.getPaidFee().add(gathering.getTotalFee()));
                officialstu.setNoPay(officialstu.getNoPay().subtract(gathering.getTotalFee()));
                officialstu.setFeeState(0);
            }
            mapper.changeState(feeId);
            //改变费用相关状态和信息
            officialstuMapper.changeFeeState(officialstu);
        }
    }

}
